package cn.linstudy.blog.handler;

import cn.linstudy.blog.enums.ErrorCodeEnum;
import cn.linstudy.blog.utils.ResponseUtils;
import cn.linstudy.blog.vo.BaseVO;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

/**
 * @Author XiaoLin
 * @Date 2021/12/22 14:05
 * @Description 登录失败处理类
 */
@Slf4j
@Component
public class UserLoginFailureHandler implements AuthenticationFailureHandler {

    /**
     * 登录失败返回结果
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        // 这些对于操作的处理类可以根据不同异常进行不同处理
        if (exception instanceof UsernameNotFoundException) {
            log.info("【登录失败】" + exception.getMessage());
            //用户名不存在
            ResponseUtils.ResponseMeg(response, new BaseVO(false, ErrorCodeEnum.NO_USER.getKey(), ErrorCodeEnum.NO_USER.getValue()));
            return;
        }
        if (exception instanceof LockedException) {
            log.info("【登录失败】" + exception.getMessage());
            //用户锁定
            ResponseUtils.ResponseMeg(response, new BaseVO(false, ErrorCodeEnum.USER_IS_LOCK.getKey(), ErrorCodeEnum.USER_IS_LOCK.getValue()));
            return;
        }
        if (exception instanceof BadCredentialsException) {
            log.info("【登录失败】" + exception.getMessage());
            //密码错误
            ResponseUtils.ResponseMeg(response, new BaseVO(false, ErrorCodeEnum.USERNAME_PASSWORD_IS_ERROR.getKey(), ErrorCodeEnum.USERNAME_PASSWORD_IS_ERROR.getValue()));
            return;
        }
    }
}
